// pages/adoptionCenter/adoptionCenter.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"),
formatTime = require("../../../component/common.js")
import Toast from '../../../component/vant/toast/toast';
import Dialog from '../../../component/vant/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeIndex: 0,
    adoptArr: [ ],
    myAdoptArr: [ ],
    navTitle: ['领养中心', '我领养的'],
    show: false,
    pageIndex:1,
    pageSize:10,
    chooseAdoptId:0,
    isiphonex: app.globalData.isiphonex,
    isxiaomi: app.globalData.isxiaomi,
    adopt_type:1,
    isCrop:0,//是否是作物 0 - 畜禽类  1 - 作物类
    chooseAdoptIds:[],
    chooseCount:0,
    emptyCount:0,
  },
  targgerTitle(event) {
    this.setData({
      activeIndex: event.target.dataset.index
    })
  },
  explainClose() {
    this.setData({
      show: false
    })
  },
  onExplain(event) {
    console.log(event);
    this.setData({
      show: true
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log('adopt_type',options);
    if(options.type){
      this.data.adopt_type = parseInt(options.type);
      this.setData({
        adopt_type: this.data.adopt_type,
      })
    }
    this.onHttpInit();
  },
  /**
   *  获取领养中心列表
   */
  onHttpInit: function () {
    var that = this;
    fetchApi.httpPost('/farm/adopt/listNew', {
      adopt_type: that.data.adopt_type,
      pageIndex: that.data.pageIndex,
      pageSize:that.data.pageSize,
    }, function (res) {
      console.log("获取领养中心列表", res)
      if (res.data.code == 0) {
        that.data.pageIndex = that.data.pageIndex + 1;
        
        that.setData({
          emptyCount: res.data.data.emptyCount
        })
        var adoptArr = res.data.data.adopts;
        if(adoptArr.length > 0){
          for (var index in adoptArr) {
            that.data.adoptArr.splice(that.data.adoptArr.length, 0, adoptArr[index]);
          }
          console.log('adoptArr',adoptArr)
          that.setData({
            hasData: true,
            adoptArr: that.data.adoptArr
          })
        }
        that.data.adoptArr = adoptArr;
      }else{
        Toast.fail(res.data.msg)
      }
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
      that.setData({ netWork: true, isLoading: false, })
    }, function () {
      that.setData({ netWork: false, hasData: false, isLoading: false })
    })
  },
  addPoultryMany(e){
    var adopt_id = e.currentTarget.dataset.adoptId;
    var index = e.currentTarget.dataset.index;
    
    if(this.data.chooseCount <= this.data.emptyCount && this.data.emptyCount > 0){
      console.log('11111')
      if(this.data.adoptArr[index].isCheck == 0){
        this.data.adoptArr[index].isCheck = 1;
        this.data.adoptArr[index].checkCount = 1;
        this.data.chooseCount += 1;
      }else{      
        this.data.adoptArr[index].isCheck = 0;
        this.data.adoptArr[index].checkCount = 0;
        this.data.chooseCount -= 1;
      }
      this.setData({
        chooseCount: this.data.chooseCount,
        adoptArr: this.data.adoptArr
      })
    }else{
      Toast("选择数量已经超过空余地块数量");
    }
    this.getTotalChooseCount();
  },
  onChangeCount(e){
    console.log('onChangeCount',e);
    var isWarn = false;
    if(this.data.chooseCount >= this.data.emptyCount){
      Toast("选择数量已经超过空余地块数量");
      isWarn = true;;
    }
    if(isWarn){
      console.log('isWarn',isWarn)
      var index = e.currentTarget.dataset.index;
      var count = e.detail - 1 ;
      this.data.adoptArr[index].checkCount = count;
      console.log('count',count);
  
    }else{
      var index = e.currentTarget.dataset.index;
      var count = e.detail;
      this.data.adoptArr[index].checkCount = count;
    }
    console.log('this.data.adoptArr',this.data.adoptArr)
    this.setData({
      adoptArr: this.data.adoptArr
    })
    this.getTotalChooseCount();
  },
  getTotalChooseCount(){
    var count = 0;
    for(var index in this.data.adoptArr){
      if( this.data.adoptArr[index].checkCount > 0){
        count += this.data.adoptArr[index].checkCount;
      }
    }
    this.data.chooseCount = count;
    this.setData({
      chooseCount: count,
    })
    if(count > this.data.emptyCount){
      Toast("选择数量已经超过空余地块数量")
    }
  },
  addPoultry(e){
    var that = this;
    var item = e.currentTarget.dataset.item;
    var isLogin = app.getStorageSync("isLogin");
    that.setData({ isLogin: isLogin})
    if(isLogin == 1){
      var adoptId = e.currentTarget.dataset.adoptId;
      var name = e.currentTarget.dataset.name;
      this.data.chooseAdoptId = adoptId;
      this.data.isCrop = item.isCrop;//是否是作物 0 - 畜禽类  1 - 作物类
      
      var title = '种植' + name;
      var message = "是否确认种植" + name + "?";
      if(item.isCrop == 0){
        wx.navigateTo({
          url: '../poultry/index?id=' + this.data.chooseAdoptId,
        })
      }else{
        Dialog.confirm({
          title: title,
          message,
        });
      }
    }else{
      wx.navigateTo({
        url: '/pages/login/index',
      })
    }
  },
  onClose(e){
    console.log('onClose',e)
    var btnType = e.detail;
    if(btnType == "cancle"){//取消操作

    } else if(btnType == "confirm"){//确认操作
      this.onHttpAddPoultry()
    }
  },
  goAddMany(e){
    if(this.data.chooseCount > this.data.emptyCount){
      Toast("选择数量已经超过空余地块数量");
      return;
    }

    this.data.chooseAdoptIds = [];
    for(var index in this.data.adoptArr){
      if(this.data.adoptArr[index].isCheck == 1){
        var adopt = 
        { 
          adopt_id: this.data.adoptArr[index].id ,
          count:  this.data.adoptArr[index].checkCount ,
        }
        this.data.chooseAdoptIds.push(adopt);
      }
    }
    console.log('chooseAdoptIds',this.data.chooseAdoptIds)
    this.onHttpAddManyPoultry();
  },
  /**
   *  获取附近的人的用户列表
   */
  onHttpAddManyPoultry() {
    var that = this;
    fetchApi.httpPost('/farm/adoptOpMany', {
      choose_adopt: that.data.chooseAdoptIds,
    }, function (res) {
      console.log("领养响应数据", res)
      if (res.data.code == 0) {
        Toast.success(res.data.msg);
        setTimeout(function(){
          wx.switchTab({
            url: '/pages/farmer/info/index',
          })
        },1000)
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {
    })
  },
  /**
   *  获取附近的人的用户列表
   */
  onHttpAddPoultry() {
    var that = this;
    fetchApi.httpPost('/farm/adoptOp', {
      adopt_id: that.data.chooseAdoptId,
    }, function (res) {
      console.log("领养响应数据", res)
      if (res.data.code == 0) {
        // var message = "您已领养成功，赠送您180g饲料";
        // Dialog.alert({
        //   theme: 'round-button',
        //   message,
        // });
        Toast.success(res.data.msg);
        setTimeout(function(){
          wx.switchTab({
            url: '/pages/farmer/info/index',
          })
        },1000)
      }else{
        Toast.fail(res.data.msg);
      }
    }, function () {
    })
  },
})